package com.silence.gmall.listener;

import com.silence.gmall.base.BaseExcelBean;
import com.silence.gmall.base.BaseExcelErrorMessage;
import com.silence.gmall.base.UploadResult;

import java.util.List;
import java.util.function.Function;

/**
 * @Author silence
 * @Email 792245022@qq.com
 * @Date 2025-06-11 14:50
 * @Description excel 上传监听器
 */
public class ExcelUploadListener<T extends BaseExcelBean> extends AbstractEasyExcelListener<T> {

    /**
     * 保存函数
     */
    private final Function<List<T>, Void> saveDataFunction;

    /**
     * 上传结果
     */
    public final UploadResult<T> uploadResult;

    /**
     * 构造方法
     *
     * @param saveDataFunction 保存函数
     * @param uploadResult     上传结果
     */
    public ExcelUploadListener(Function<List<T>, Void> saveDataFunction, UploadResult<T> uploadResult) {
        this.saveDataFunction = saveDataFunction;
        this.uploadResult = uploadResult;
    }

    /**
     * 保存数据
     *
     * @param orderUploadList 数据列表
     */
    @Override
    protected void saveData(List<T> orderUploadList) {
        if (uploadResult != null) {
            uploadResult.getData().addAll(orderUploadList);
            uploadResult.getSuccessDate().addAll(orderUploadList);
        }
        if (saveDataFunction != null) {
            saveDataFunction.apply(orderUploadList);
        }
    }

    /**
     * 获取结果
     *
     * @return 上传结果
     */
    public UploadResult<T> getResult() {
        return this.uploadResult;
    }

    /**
     * 获取结果
     *
     * @param errorMessages 错误消息
     * @return 结果
     */
    public UploadResult<T> getResult(List<BaseExcelErrorMessage> errorMessages) {
        if (errorMessages != null) {
            errorMessages.forEach(v -> {
                int row = v.getRow();
                if (uploadResult.getData().size() > row + 1) {
                    T t = uploadResult.getData().get(row);
                    t.setErrorMsg(v.getMessage());
                    uploadResult.getData().set(row, t);
                }
            });
        }
        return this.uploadResult;
    }
}
